package org.gujia.seckill.service.impl;

import org.gujia.seckill.dao.SeckillDao;
import org.gujia.seckill.dao.SuccessKilledDao;
import org.gujia.seckill.dao.cache.RedisDao;
import org.gujia.seckill.dto.Exposer;
import org.gujia.seckill.dto.SeckillExecution;
import org.gujia.seckill.entity.Seckill;
import org.gujia.seckill.entity.SuccessKilled;
import org.gujia.seckill.enums.SeckillStateEnum;
import org.gujia.seckill.exception.RepeatKillException;
import org.gujia.seckill.exception.SeckillCloseException;
import org.gujia.seckill.exception.SeckillException;
import org.gujia.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by GuJia on 2017/2/14.
 */
//@Component 所有的组件 @Service @Dao @Controller
@Service
public class SeckillServiceImpl implements SeckillService{

    Logger logger = LoggerFactory.getLogger(this.getClass());

    private  final String slat = "qwyuae42343586^&%&%^853**";
    //注入service依赖
    //@Resource
    @Autowired
    private SeckillDao seckillDao;

    @Autowired
    private SuccessKilledDao successKilledDao;

    @Autowired
    private RedisDao redisDao;

    public List<Seckill> getSeckillList() {
        return seckillDao.queryAll(0,10);
    }

    public Seckill getById(long seckillId) {
        return seckillDao.queryById(seckillId);
    }

    public Exposer exportSeckillUrl(long seckillId) {
        //优化点  缓存优化  超时的基础上维护一致性
        //1:访问 redis
        Seckill seckill = redisDao.getSeckill(seckillId);
        if(null== seckill){
            //2：访问数据库
            seckill = seckillDao.queryById(seckillId);
            if(null==seckill){
                return new Exposer(false,seckillId);
            }else{
                //3：放入redis
                redisDao.putSeckill(seckill);
            }
        }

        Date startTime = seckill.getStartTime();
        Date endTime = seckill.getEndTime();
        Date nowTime = new Date();
        if(nowTime.getTime()<startTime.getTime() || nowTime.getTime()>endTime.getTime()){
            return new Exposer(false,seckillId,nowTime.getTime(),startTime.getTime(),endTime.getTime());
        }

        String md5 =getMD5(seckillId);

        return new Exposer(true,md5,seckillId);
    }

    /**
     * 将seckillId转换为MD5
     * @param seckillId
     * @return
     */
    private  String getMD5(long seckillId){
        String base = seckillId +"/"+slat;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());

        return  md5;
    }

    /**
     * 使用注解控制事务方法的优点：
     * 1：开发团队达成一致约定，明确标注事物方法的编程风格
     * 2：保证事务方法的执行时间尽可能短，不要穿插其他的网络操作RPC/HTTP请求操作或者剥离到事物方法外
     * 3：不是所有的方法都需要事务，如只有一条修改操作，只读操作不需要事务控制
     */
    @Transactional
    public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5)
                    throws SeckillException, RepeatKillException, SeckillCloseException {


       if(null == md5 || !md5.equals(getMD5(seckillId))){
           throw  new SeckillException("seckill data rewrite");
       }
        //执行秒杀逻辑：减库存+记录购买行为
       Date now = new Date();
      try {
                //减少rowLock持有行级锁的时间
                //记录购买行为
              int insertCount = successKilledDao.insertSuccessKilled(seckillId, userPhone);

              if (insertCount <= 0) {

                  throw new RepeatKillException("seckill repeated");

              } else {
                  int updateCount = seckillDao.reduceNumber(seckillId, now);

                  if (updateCount <= 0) {
                      //没有更新到记录，秒杀结束
                      throw new SeckillCloseException("seckill is closed");
                  }
                  //秒杀成功
                  SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
                  return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successKilled);
              }

      }catch (SeckillCloseException e){
         throw e;
      }catch (RepeatKillException e){
          throw e;
      }catch (Exception e){
          logger.error(e.getMessage(),e);
          throw new SeckillException("seckill inner error:"+e.getMessage());
      }


    }
}
